package com.gxa.community.admin.realm;

import com.gxa.community.admin.realm.Auth2Token.Auth2Token;
import com.gxa.community.admin.service.system.LoginService;
import com.gxa.community.admin.util.JwtUtil;
import com.gxa.community.core.pojo.domain.Admin;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.apache.commons.lang.StringUtils;

import java.util.Set;

@Component
public class UserRealm extends AuthorizingRealm {
    @Autowired
    LoginService loginService;
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof Auth2Token;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String name = JwtUtil.getSubject(principalCollection.toString());

        Set<String> permissions = loginService.queryPermissions(name);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        info.setStringPermissions(permissions);

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String token = (String) authenticationToken.getCredentials(),
                uname = JwtUtil.getSubject(token);
        if (StringUtils.isNotBlank(uname)) {
            Admin user = loginService.queryAdminByName(uname);
            // 校验token
            if (JwtUtil.verify(token, uname, user.getPassword())) {
                //验证成功将用户信息存入redis
                return new SimpleAuthenticationInfo(authenticationToken.getCredentials(), authenticationToken.getCredentials(), getName());
            }
        }
        return null;
    }
}
